﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.Provider
{
    public class ConfigurationProvider : GenericProvider, IConfigurationProvider
    {
        public Dictionary RetrieveDictionary(Guid applicationKey, string key)
        {
            var appkey = applicationKey.ToString();
            key = key ?? "UnknowKey";
            return repository.Find<Dictionary>(x => x.ApplicationKey.ToUpper() == appkey.ToUpper() && x.Key == key).FirstOrDefault();
        }

        public string[] DeleteDictionaries(Guid applicationKey, params string[] keys)
        {
            if (keys == null || keys.Length == 0) return new string[] { };
            List<string> result = new List<string>();
            foreach (var key in keys)
            {
                try
                {
                    repository.Delete<Dictionary>(x => key == x.Key);
                    repository.UnitOfWork.SaveChanges();
                    result.Add(key);
                }
                catch
                {
                }
            }
            return result.ToArray();
        }


        public Dictionary AddDictionary(Dictionary dictionary)
        {
            try
            {
                repository.Add<Dictionary>(dictionary);
                repository.UnitOfWork.SaveChanges();
            }
            catch
            {
                return null;
            }
            return dictionary;
        }


        public List<Dictionary> SearchDictionaries(Guid applicationKey, double? lifeTime)
        {
            var appkey = applicationKey.ToString();
            var dictQuerry = repository.Find<Dictionary>(x => x.ApplicationKey.ToUpper() == appkey.ToUpper());

            if (lifeTime.HasValue && lifeTime > 0)
            {
                DateTime time = DateTime.Now.AddMinutes(-lifeTime.Value);
                dictQuerry = dictQuerry.Where(x => x.CreationDate <= time);
            }
            return dictQuerry.ToList();
        }


        public bool UpdateAppError(ApplicationError appError)
        {
            throw new NotImplementedException();
        }

        public List<ApplicationError> SearchAppError(out int totalRecord, bool? nullable, int pageSize, int pageIndex)
        {
            throw new NotImplementedException();
        }
    }
}
